/**
 * 
 */
package org.jenkon.commons.lang.converter;

import java.io.Serializable;

/**
 * @author Jens Konopka
 * 
 */
public class BooleanConverter implements Converter<Object, Boolean>,
		Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4204941328308853863L;

	private final Boolean defaultValue;
	private final boolean useDefault;

	/**
	 * 
	 */
	public BooleanConverter() {
		this(false);
	}

	/**
	 * @param useDefault
	 */
	public BooleanConverter(final boolean useDefault) {
		this(useDefault, null);
	}

	/**
	 * @param useDefault
	 * @param defaultValue
	 */
	public BooleanConverter(final boolean useDefault, final Boolean defaultValue) {
		this.useDefault = useDefault;
		this.defaultValue = defaultValue;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jenkon.converter.Converter#convert(java.lang.Object)
	 */
	public Boolean convert(final Object value) {

		if (value == null) {
			if (useDefault) {
				return defaultValue;
			} else {
				throw new ConversionException("parameter has not value.");
			}
		} else if (value instanceof Boolean) {
			return (Boolean) value;
		} else if (value instanceof String) {
			return isPositiv(String.valueOf(value));
		} else if (value instanceof Number) {
			return isPositiv(Double.valueOf(String.valueOf(value)));
		}

		throw new ConversionException("cannot convert the " + value);
	}

	/**
	 * @param value
	 * @return
	 */
	private boolean isPositiv(final Number value) {
		return value.doubleValue() > 0;
	}

	/**
	 * @param value
	 * @return
	 */
	private boolean isPositiv(final String value) {
		return value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("true")
				|| value.equalsIgnoreCase("1");
	}

}
